package com.happy3w.cmds.install;

import com.beust.jcommander.Parameter;
import com.happy3w.cmds.command.ArgAppCmd;
import com.happy3w.cmds.command.NoneSplitter;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

@Slf4j
@Component
public class GenInstallShellCmd extends ArgAppCmd<GenInstallShellCmd.Args> {
    private final JarInfoDetector jarInfoDetector;

    public GenInstallShellCmd(JarInfoDetector jarInfoDetector) {
        super(GenInstallShellCmd.Args.class);
        this.jarInfoDetector = jarInfoDetector;
    }

    @Getter
    @Setter
    public static class Args {
        @Parameter(names = {"-i", "--in"}, description = "dir for input libs", required = true, splitter = NoneSplitter.class)
        private List<String> inputDirs = new ArrayList<>();

        @Parameter(names = {"-o", "--output"}, description = "output file")
        private String outputFile;
    }

    @Override
    public String getName() {
        return "gen-install-shell";
    }

    @Override
    public void runWithArg(Args args) throws Exception {
        List<String> commands = new ArrayList<>();
        List<String> missingPomJars = new ArrayList<>();

        for (String dir : args.inputDirs) {
            processDirectory(dir, commands, missingPomJars);
        }

        PrintStream output = System.out;
        if (StringUtils.hasText(args.outputFile)) {
            output = new PrintStream(args.outputFile);
        }
        outputResults(commands, missingPomJars, output);
    }

    private void processDirectory(String dirPath, List<String> commands, List<String> missingPomJars) {
        File dir = new File(dirPath);
        if (!dir.exists() || !dir.isDirectory()) {
            System.err.println("目录不存在或不是一个有效目录: " + dirPath);
            return;
        }

        try {
            // 遍历目录中的所有JAR文件，不处理子目录
            Files.list(Paths.get(dirPath))
                    .filter(Files::isRegularFile)
                    .filter(path -> path.getFileName().toString().endsWith(".jar"))
                    .map(Path::toFile)
                    .forEach(jarFile -> processJarFile(jarFile, commands, missingPomJars));
        } catch (IOException e) {
            System.err.println("处理目录 " + dirPath + " 时出错: " + e.getMessage());
        }
    }

    private void processJarFile(File jarFile, List<String> commands, List<String> missingPomJars) {
        try {
            LibConfig libConfig = jarInfoDetector.detect(jarFile);
            if (libConfig != null) {
                commands.add(libConfig.buildInstallCmd());
            } else {
                missingPomJars.add(jarFile.getAbsolutePath());
            }
        } catch (Exception e) {
            System.err.println("处理JAR文件 " + jarFile.getAbsolutePath() + " 时出错: " + e.getMessage());
            missingPomJars.add(jarFile.getAbsolutePath() + " (处理出错)");
        }
    }

    private void outputResults(List<String> commands, List<String> missingPomJars, PrintStream output) {
        Stream.of(commands, missingPomJars)
                .flatMap(List::stream)
                .forEach(output::println);
    }
}
